package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import Other.Glob;
import database.DatabaseExtension;
import database.DatabaseMySQL;
import database.MyPayment;
import database.NewTirDataBase;
import enums.DialogType;
import enums.SearchType;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.ArrayList;
public class Payment extends JFrame {
	//variable for singleton
	private static Payment paymentInstance = null;
	private JPanel contentPane;
	private JTextField tfCode;
	private JTextField tfName;
	//variable that represent this window frame
	private JFrame thisFrame = this;
	//SearchType type;
	boolean disable;
	private Payment() {
		setTitle("Payment");
		setVisible(true);
		//set resizable
		setResizable(false);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 639, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		JPanel mainPanel = new JPanel();
		mainPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		JPanel buttonPanel = new JPanel();
		buttonPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(mainPanel, GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
				.addComponent(buttonPanel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(buttonPanel, GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)
					.addGap(5))
		);
		JButton btnSave = new JButton("F4 Save");
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//Save when button pressed
				saveDialog();
			}
		});
		tfCode = new JTextField();
		tfCode.getInputMap(tfCode.WHEN_IN_FOCUSED_WINDOW)
		//setting up F4 for saving
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "Save");
		tfCode.getActionMap().put("Save", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 saveDialog();
			 }
		});
		JButton btnRemove = new JButton("F6 Remove");
		//set up F6 for removing
		btnRemove.getInputMap(btnRemove.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), "");
		btnRemove.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 //remove item when F6 button pressed
			
				 ScreenHandling.remove(tfCode, SearchType.PAYMENT);
			    }
		});
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//remove item when button pressed
				
				ScreenHandling.remove(tfCode, SearchType.PAYMENT);
			}
		});
		JButton btnFReset = new JButton("F7 Reset");
		//set up F7 for reset
		btnFReset.getInputMap(btnFReset.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), "");
		btnFReset.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 resetFields();
			    }
		});
		btnFReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resetFields();
			}
		});
		JButton btnEscExit = new JButton("Esc Exit");
		//set up Escape for exit
		btnEscExit.getInputMap(btnEscExit.WHEN_IN_FOCUSED_WINDOW)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "");
		btnEscExit.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
					if (disable == false){
						escape();
					}
			    }
		});
		btnEscExit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (disable == false){
					escape();
				}
			}
		});
		GroupLayout gl_buttonPanel = new GroupLayout(buttonPanel);
		gl_buttonPanel.setHorizontalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_buttonPanel.createSequentialGroup()
					.addGap(18)
					.addComponent(btnRemove)
					.addPreferredGap(ComponentPlacement.RELATED, 220, Short.MAX_VALUE)
					.addComponent(btnEscExit)
					.addGap(29)
					.addComponent(btnFReset)
					.addGap(34)
					.addComponent(btnSave)
					.addGap(18))
		);
		gl_buttonPanel.setVerticalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_buttonPanel.createSequentialGroup()
					.addGap(21)
					.addGroup(gl_buttonPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnSave)
						.addComponent(btnRemove)
						.addComponent(btnFReset)
						.addComponent(btnEscExit))
					.addContainerGap(38, Short.MAX_VALUE))
		);
		buttonPanel.setLayout(gl_buttonPanel);
		JLabel codeLabel = new JLabel("Code");
		JLabel lblName = new JLabel("Payment Type");
		//set up F5 for saving only when the text is focused
		tfCode.getInputMap(tfCode.WHEN_FOCUSED)
		.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "");
		tfCode.getActionMap().put("", new AbstractAction() {
			 public void actionPerformed(ActionEvent e) {
				 //when textcode focused and f5 pressed search dialog comes up
				search();
			    }
		});
		JButton searchButton = new JButton("F5 Search");
		searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				search();
			}
		});
		tfCode.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a number is entered with ENTER
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
					
					ScreenHandling.enterData(tfCode, tfName, tfName, SearchType.PAYMENT);
					//tfName.requestFocus();
				}
			}
		});
		tfCode.setColumns(10);
		tfName = new JTextField();
		tfName.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				//when a number is entered
				if(e.getKeyChar() == KeyEvent.VK_ENTER){
					//request focus for the next fields
					tfCode.requestFocus();				
				}
			}
		});
		tfName.setColumns(10);
		GroupLayout gl_mainPanel = new GroupLayout(mainPanel);
		gl_mainPanel.setHorizontalGroup(
			gl_mainPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addGap(42)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(codeLabel, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblName))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.LEADING, false)
						.addComponent(tfName)
						.addComponent(tfCode, GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(searchButton)
					.addContainerGap(284, Short.MAX_VALUE))
		);
		gl_mainPanel.setVerticalGroup(
			gl_mainPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mainPanel.createSequentialGroup()
					.addGap(37)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(codeLabel)
						.addComponent(tfCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(searchButton))
					.addGap(18)
					.addGroup(gl_mainPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblName)
						.addComponent(tfName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(70, Short.MAX_VALUE))
		);
		//request focus when object is called
		tfCode.requestFocus(true);
		mainPanel.setLayout(gl_mainPanel);
		contentPane.setLayout(gl_contentPane);
	}
//singleton
public static Payment getInstance(){
	if(paymentInstance == null){
		paymentInstance = new Payment();
	}
	return paymentInstance;
	}
//initiate data
public void init(MyPayment payment){
	tfCode.setText(payment.getPaymentID());
	tfName.setText(payment.getPaymentName());
}
//method needed to set focus from other screens
public void setTextCodeFocus(){
	tfCode.requestFocus();
}
//reset fields
public void resetFields(){
	tfCode.setText("");
	tfName.setText("");
	setTextCodeFocus();
}
//method needed to get value from text code in other screens
public String getFieldText() {
    return tfCode.getText();
 }
public void saveDialog(){
	Glob.setDialog(DialogType.OVERWRITE);
	try{
		if(tfName.getText().trim().length()<1 || Integer.parseInt(tfCode.getText()) <= 0) {
			JOptionPane.showMessageDialog(null, "Name may not be empty and Code has to be a valid number");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
		}
if(!tfCode.getText().trim().isEmpty()) {
			
			if(Integer.parseInt(tfCode.getText())<1){
				JOptionPane.showMessageDialog(null, "Code has to be a valid number");
				tfCode.setText("");
				tfCode.requestFocus();
				return;
				
			}
			}
	ArrayList<Integer> ids = DatabaseExtension.columnIDs("Select * from payment");
		System.out.println(ids);
		boolean ok = false;
		for (int i: ids) {
			if (i == Integer.parseInt(tfCode.getText()))
					ok=true;
		}
			if (ok) {
			//JOptionPane.showMessageDialog(null, "This ID is already on the table, ");
			Dialog d = Dialog.getInstance();
			d.setVisible(true);
			Payment.getInstance().disablePayment();
			//tfCode.requestFocus();
			return;
		}else{
			save();
		}
	}catch (NumberFormatException e){
		save();
			}
}
//method for saving the object
public void save(){
	try {
		Glob.setType(SearchType.PAYMENT);
	String[] data = new String[2];	
	data[0] = tfCode.getText();			
	if(data[0].isEmpty()){
	data[0] = null;
	}
data[1] = tfName.getText();
	MyPayment payment = new MyPayment(data);
		DatabaseExtension.savePayment(payment);
		resetFields();
		setTextCodeFocus();
	} catch (SQLException e) {
		JOptionPane.showMessageDialog(null, "Code must be a number");
		e.printStackTrace();
		tfCode.setText("");
		tfCode.requestFocus();
		return;
	}catch (NumberFormatException e){
		JOptionPane.showMessageDialog(null, "Code must be a number");
		e.printStackTrace();
		tfCode.setText("");
		tfCode.requestFocus();
		return;
	}catch (Exception exception){
		exception.printStackTrace();
	}	
}
//method that calls the searchwindow
public void search(){
	Glob.setType(SearchType.PAYMENT);
	//System.out.println("This is the globa variable in Payment when pressing search button" + Glob.type);

	//MyPayment payment = new MyPayment(); 
	SearchWindow s = SearchWindow.getInstance();
	s.setTitle();
	s.setVisible(true);
	disablePayment();
	
}
public void disablePayment(){
	Payment.getInstance().disable();
	disable = true;
}
public void enablePayment(){
	Payment.getInstance().enable();
	disable = false;
	tfCode.requestFocus();
	Payment.getInstance().toFront();
}
public boolean getDisable(){
	return disable;
}
//method that calls the dialog screen
/**W
public void remove(){
	//set up global variable for this screen
	Glob.type = SearchType.PAYMENT;
	//set up global variable for deleting an item
	Glob.dialog= DialogType.DELETE;
	try{
if(Integer.valueOf(tfCode.getText()) <= 0) {
			JOptionPane.showMessageDialog(null, "Code may not be empty and must have a proper ID");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
		}
		ArrayList<Integer> ids = DatabaseExtension.columnIDs("Select * from Payment");
		System.out.println(ids);
		boolean ok = false;
		for (int i: ids) {
			if (i == Integer.valueOf(tfCode.getText()))
					ok=true;
		}
			if (!ok) {
			JOptionPane.showMessageDialog(null, "This ID is not in the payment table");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
		}
		Dialog d = Dialog.getInstance();
		d.setVisible(true);
		disablePayment();
		}catch(Exception z){
			JOptionPane.showMessageDialog(null, "Code may not be empty and must have a proper ID");
			tfCode.requestFocus();
			tfCode.setText(null);
			z.printStackTrace();
		}
}
*/
/**
public void enterData(){
	try{
		//set up global variable for this screen
		Glob.type = SearchType.PAYMENT;
		if(Integer.valueOf(tfCode.getText()) <= 0){
			JOptionPane.showMessageDialog(null, "Code must be a positive number");
			tfCode.setText("");
			tfCode.requestFocus();
			return;
		}
	//Select the row that will populate the screen
	NewTirDataBase p = (MyPayment) DatabaseExtension.getTableID( "SELECT * FROM Payment WHERE PaymentID = '" + tfCode.getText() +"'")[0];
	System.out.println("This is the payment id" +((MyPayment) p).getPaymentID());
	System.out.println("This is the payment name" +((MyPayment) p).getPaymentName());
	//populating the fields
	tfName.setText(((MyPayment) p).getPaymentName());
	System.out.println("intro has been pressed");
	//requestfocus for the next field when pressing enter
	tfName.requestFocus();
	}catch(ArrayIndexOutOfBoundsException exception){
		System.out.println("This is the exception release when id not in database");
		//if there is no id in the database tfName set to empty
		tfName.setText(null);
		exception.printStackTrace();
		//requestfocus for the next field when pressing enter
		tfName.requestFocus();
	}catch(NumberFormatException exception){
		if(tfCode.getText().trim().length()<1){
			tfName.requestFocus();
			return;
		}else{
			tfCode.setText(null);
			JOptionPane.showMessageDialog(null, "Code must be a positive number");
			tfCode.requestFocus();
		} 
		System.out.println("This is the exception release when there is an String");
		exception.printStackTrace();
	}catch(Exception exception){
		System.out.println("General Exception");
		exception.printStackTrace();
	}
	
}
*/
	public void escape(){
		Payment.getInstance().dispose();
		Menu.getInstance().enableMenu();
	}
}